package com.example.config;


import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class ZkApi {

    private static final Logger logger= LoggerFactory.getLogger(ZkApi.class);

    @Autowired
    @Qualifier(value = "zookeeperClient")
    private ZooKeeper zkClient;

    public Stat exists(String path,boolean needWatcher){
        try{
            return zkClient.exists(path,needWatcher);
        }catch (Exception e){
            logger.error("判断节点是否存在异常 {} ,{}",path,e);
            return null;
        }
    }

    public Stat exists(String path, Watcher watcher){
        try{
            return zkClient.exists(path,watcher);
        }catch (Exception e){
            logger.error("判断节点是否存在异常 {},{}",path,e);
            return null;
        }
    }

    public boolean createNode(String path,String data){
        try{
            zkClient.create(path,data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            return true;
        }catch (Exception e){
            logger.error("创建持久化节点异常  {},{},{}",path,data,e);
            return false;
        }
    }

    public boolean updateNode(String path,String data){
        try{
            zkClient.setData(path,data.getBytes(),-1);
            return true;
        }catch (Exception e){
            logger.error("修改持久化节点异常 {},{},{}",path,data,e);
            return false;
        }
    }

    public boolean deleteNode(String path){
        try{
            zkClient.delete(path,-1);
            return true;
        }catch (Exception e){
            logger.error("删除持久化节点异常 {},{}",path,e);
            return false;
        }
    }
    public List<String> getChildren(String path) throws KeeperException, InterruptedException {
        return zkClient.getChildren(path,false);
    }

    public String getData(String path,Watcher watcher){
        try{
            Stat stat = new Stat();
            byte[] data = zkClient.getData(path, watcher, stat);
            return new String(data);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @PostConstruct
    public void init(){
        String path = "/zk-watcher";
        logger.info("执行初始化测试方法......");
        createNode(path,"test");
        String data = getData(path, new WatcherApi());
        logger.info("执行初始化测试方法返回的值为:{}",data);
        deleteNode(path);

    }
}
